﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class PhonicsScrollPage : MonoBehaviour, IEndDragHandler {

	private Scrollbar scrollbar;

	private float targetValue;

	private float moveValue;

	public int PageNum = 1;

	private float preValue;

	private int curPage = 1;

	private float curValue;

	private bool needMove;

	private bool moving;

	private float mMoveSpeed = 0f;

	// Use this for initialization
	void Start () {
		scrollbar = GetComponent<ScrollRect> ().horizontalScrollbar;
		preValue = 1f / (PageNum -1);
		curPage = 1;
		curValue = 0f;
	}
	
	// Update is called once per frame
	void Update () {
		if (needMove) {
			if (Mathf.Abs (scrollbar.value - targetValue) < 0.01f) {
				scrollbar.value = targetValue;
				needMove = false;
				moving = false;
				return;
			}
			moving = true;
			scrollbar.value = Mathf.SmoothDamp (scrollbar.value, targetValue, ref mMoveSpeed, 0.2f);
		}
	}

	public void OnEndDrag (PointerEventData eventData) {

		if (moving) {
			return;
		}

		needMove = true;
		moveValue = scrollbar.value;
		if (moveValue > curValue + preValue/2) {
			NextPage ();
		} else if (moveValue < curValue - preValue/2) {
			PrePage ();
		} else {
			CurPage ();
		}
		//Debug.Log (moveValue);
		//Debug.Log (targetValue);
	}

	private void NextPage() {
		targetValue = curValue + preValue;
		curValue = targetValue;
		curPage++;
	}

	private void PrePage() {
		targetValue = curValue - preValue;
		curValue = targetValue;
		curPage--;
	}

	private void CurPage() {
		targetValue = curValue;
	}
}
